<template>
  <div class="search-result">
    <van-list v-model="loading"
      :error.sync="error"
      :finished="finished"
      finished-text="没有更多了"
      error-text="请求失败，点击重新加载"
      @load="onLoad">
      <van-cell v-for="(item,index) in resultList"
        :key="index"
        :title="item.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search'
export default {
  name: 'SearchResult',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      resultList: [],
      loading: false,
      error: false,
      finished: false,
      page: 1, // 页码
      per_page: 10 // 每页数据条数
    }
  },
  methods: {
    async onLoad () {
      // 1、请求获取数据
      try {
        const res = await getSearchResult({
          page: this.page,
          per_page: this.per_page,
          q: this.searchText
        })
        // console.log(res)
        // 2. 将数据添加到列表中
        const { results } = res.data.data
        this.resultList.push(...results)
        // 3. 关闭本次加载状态
        this.loading = false

        // 4. 判断数据是否加载完毕
        if (results.length) {
          this.page++
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
